package com.example.imgrecognition.Activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.imgrecognition.R;
import com.zk.code.net.FileUtil;
import com.zk.code.net.NetUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
接收服务端命令 拍照界面
 */
public class TakeOneShotActivity extends Activity implements SurfaceHolder.Callback,Camera.PictureCallback{
    private SurfaceView mSurfaceView;
    private ImageView mIvStart;
    private TextView mTvCountDown;

    private SurfaceHolder mHolder;

    private Camera mCamera;

    private Handler mHandler = new Handler();

    private int mCurrentTimer = 1;

    private boolean mIsSurfaceCreated = false;
    private boolean mIsTimerRunning = false;
    int compression;

    private static int CAMERA_ID = 0; //后置摄像头
    //    private static final int CAMERA_ID = 1; //前置摄像头
    private static final String TAG = TakeOneShotActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_one_shot);
        int channle =  getIntent().getIntExtra("channle",0);
        compression =  getIntent().getIntExtra("compression",0);
        if(channle == 1){
            CAMERA_ID = 0;
        }else if(channle == 2){
            CAMERA_ID = 1;
        }else{
            CAMERA_ID = 0;
        }
        initView();
        initEvent();
        mHandler.postDelayed(timerRunnable,1000);
       /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);
            }
        }*/
        //takePic();
    }
    @Override
    protected void onPause() {
        super.onPause();
        stopPreview();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            if(mCamera!=null){
                mCamera.takePicture(null, null, null, TakeOneShotActivity.this);
                playSound();

            }
        }
    };

    private void takePic(){
        if(mCamera!=null){
            mCamera.takePicture(null, null, null, TakeOneShotActivity.this);
            playSound();
            finish();
        }
    }

    private void initView() {
        mIsTimerRunning = true;
        mSurfaceView = (SurfaceView) findViewById(R.id.surface_views);
        // mIvStart = (ImageView) findViewById(R.id.start);
        mTvCountDown = (TextView) findViewById(R.id.count_downs);
    }
    private void initEvent() {
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        mIsSurfaceCreated = true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mIsSurfaceCreated = false;
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        try {
            Log.e("是否执行--->","是");
            String files = Environment.getExternalStorageDirectory() + File.separator +
                            System.currentTimeMillis() + ".jpg";
            FileOutputStream fos = new FileOutputStream(new File(files));

            //旋转角度，保证保存的图片方向是对的
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            Matrix matrix = new Matrix();
            matrix.setRotate(90);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100 , fos);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;//直接设置它的压缩率，表示1/2
            //String picpress = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
            fos.flush();
            fos.close();
            //byte[] imgarr = FileUtil.imageToBytes(files);

            bitmap = BitmapFactory.decodeFile(files, options);
            bitmap.compress(Bitmap.CompressFormat.JPEG, compression, bos);
            final byte[] imgarr = bos.toByteArray();
            bos.flush();
            bos.close();
            Toast.makeText(TakeOneShotActivity.this,"len-->"+imgarr.length,Toast.LENGTH_SHORT).show();
            Log.e("len","lensss-->"+imgarr.length);
            NetUtil.uploadControlPic(imgarr,TakeOneShotActivity.this);
            //finish();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mCamera.startPreview();
        finish();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


    private void startPreview() {
        if (mCamera != null || !mIsSurfaceCreated) {
            Log.d(TAG, "startPreview will return");
            return;
        }
        if(mCamera==null) {
            mCamera = Camera.open(CAMERA_ID);
        }
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setJpegQuality(10);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        Camera.Size size = getBestPreviewSize(width, height, parameters);
        if (size != null) {
            //设置预览分辨率
            parameters.setPreviewSize(size.width, size.height);
            //设置保存图片的大小
            // parameters.setPictureSize(size.width, size.height);

        }

        //自动对焦
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        parameters.setPreviewFrameRate(20);

        //设置相机预览方向
        mCamera.setDisplayOrientation(90);

        mCamera.setParameters(parameters);

        try {
            mCamera.setPreviewDisplay(mHolder);
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }

        mCamera.startPreview();
    }

    private void stopPreview() {
        //释放Camera对象
        if (mCamera != null) {
            try {
                mCamera.setPreviewDisplay(null);
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    private Camera.Size getBestPreviewSize(int width, int height,
                                           Camera.Parameters parameters) {
        Camera.Size result = null;

        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;

                    if (newArea > resultArea) {
                        result = size;
                    }
                }
            }
        }

        return result;
    }
    public void playSound() {
        MediaPlayer mediaPlayer = null;
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int volume = audioManager.getStreamVolume( AudioManager.STREAM_NOTIFICATION);

        if (volume != 0) {
            if (mediaPlayer == null)
                mediaPlayer = MediaPlayer.create(this,
                        Uri.parse("file:///system/media/audio/ui/camera_click.ogg"));
            if (mediaPlayer != null) {
                mediaPlayer.start();
            }
        }
    }

}
